<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button type="danger" size="small" @click="exportExcel">excel导出</el-button>
          <el-button type="primary" size="small" @click="showAddEmployeeDialog">新增员工</el-button>
        </template>
      </page-tools>

      <el-card v-loading="loading" style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" width="100" :index="indexMethod" />
          <el-table-column label="头像" prop="staffPhoto">
            <template #default="{row}">
              <img v-imagerror="errorImg" :src="row.staffPhoto || defaultImage" alt="" class="avator_photo" @click="showImgDialogFn(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="getEmploymentText">
            <!-- <template #default="{row}">
              {{ getEmploymentText(row.formOfEmployment) }}
            </template> -->
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template #default="{row}">
              {{ row.timeOfEntry | formatTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRoleDialog(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            layout="prev, pager, next"
            :page-size="size"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>

      <addEmployees :show-dialog.sync="showDialog" />

      <el-dialog
        :visible.sync="DialogShow"
        title="二维码图片"
        :close-on-click-modal="false"
        @close="closeDialog"
      >
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>

      <assignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getUserListApi, delEmployeeApi } from '@/api/emploess'
import enumObj from '@/constant/employees'
import addEmployees from './components/add-employees.vue'
import { formatTime } from '@/filters'
import errorImg from '@/assets/common/404.jpg'
import QrCode from 'qrcode'
import assignRole from './components/assign-role.vue'
export default {
  name: 'Dashboard',
  components: {
    addEmployees,
    assignRole
  },
  data() {
    return {
      page: 1,
      size: 10,
      list: [],
      total: 0,
      loading: false,
      hireType: enumObj.hireType,
      showDialog: false,
      // 处理没有图片的情况
      defaultImage: 'https://img2.baidu.com/it/u=2203692359,101708973&fm=253&fmt=auto&app=138&f=PNG?w=401&h=401',
      // 处理碎图的情况
      errorImg: errorImg,
      DialogShow: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      this.loading = true
      const { data: { rows, total }} = await getUserListApi(this.page, this.size)
      console.log('获取员工列表成功', rows)
      this.total = total
      this.list = rows
      this.loading = false
    },
    handleCurrentChange(val) {
      this.page = val
      this.getUserList()
    },
    indexMethod(index) {
      return (this.page - 1) * this.size + index + 1
    },
    getEmploymentText(row, column, cellVlue, index) {
      const obj = this.hireType.find(item => item.id === parseInt(cellVlue))
      return obj ? obj.value : '未知'
    },
    delEmployee(id) {
      this.$confirm('亲,确认删除吗', '温馨提示').then(async() => {
        const res = await delEmployeeApi(id)
        console.log('删除成功', res)
        this.$message.success('删除成功')
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.getUserList()
      }).catch(err => {
        console.log(err)
      })
    },
    showAddEmployeeDialog() {
      this.showDialog = true
    },
    async exportExcel() {
      const { data: { rows }} = await getUserListApi(1, this.total)
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      // 多级表头（了解）
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const exportData = this.formateExportData(rows, headersArr, headersRelations)
      console.log(exportData)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          // excel的表头
          header: headersArr,
          // excel的数据,data是一个二维数组
          data: exportData,
          // 导出的文件名
          filename: '员工信息',
          // 宽度是否自适应
          autoWidth: true,
          // 文件的后缀名
          bookType: 'xlsx',
          // 多级表头
          multiHeader,
          // 合并
          merges
        })
      })
    },
    formateExportData(rows, headersArr, headersRelations) {
      console.log('获取所有数据成功', rows)
      const arr = []
      rows.forEach((item, index) => {
        const arrs = []
        headersArr.forEach(key => {
          const englishKey = headersRelations[key]
          let value = item[englishKey]
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            value = formatTime(item[englishKey])
          }
          if (englishKey === 'formOfEmployment') {
            const flag = this.hireType.find(items => items.id === parseInt(item[englishKey]))
            value = flag ? flag.value : '未知'
          }
          arrs.push(value)
        })
        arr.push(arrs)
      })
      // console.log(arr)
      return arr
    },
    showImgDialogFn(url) {
      if (!url) {
        this.$message.error('当前用户没有头像')
        return
      }
      this.DialogShow = true
      // 判断是不是默认图或者碎图

      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    closeDialog() {
      this.DialogShow = false
    },
    // 修改角色弹框
    editRoleDialog(id) {
      this.showRoleDialog = true
      // console.log(id)
      this.userId = id
    }
  }
}
</script>

<style lang="scss" scoped>
  .avator_photo{
    width: 70px;
    height: 70px;
    display: block;
    margin: 0 auto;
    border-radius: 50%;
  }
  ::v-deep
  .el-dialog__header {
    background: #66b1ff;

    .el-icon-close:before {
      color: #fff;
    }

    .el-dialog__title {
      color: #fff;
    }

  }
</style>
